

let mwindow;
if(typeof window === 'undefined') {
    mwindow = global;
} else {
    mwindow = window;
}


export default class Watcher {
    // 监听一个属性
    constructor(data,pathOrExpr,listener) {
        this.getVal = generateGetter(data,pathOrExpr);
        this.listener = listener
        // 将自己加入到dep依赖列表中
        mwindow.$MyTarget = this;
        this.getVal();
        mwindow.$MyTarget = null;
    }
    update(newV,oldV) {
        this.listener.update(newV,oldV);
    }
}


// 根据路径取得属性的值
const generateGetter = function(data,path) {
    let args = path.split(".");
    return function() {
        for(let i=0;i<args.length;i++) {
            if(!data)throw Error("generateGetter: Wrong data or path")
            data = data[args[i]];
        }
        return data;
    }
}

